/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package fr.cpe.dp.projet2.model.musicPlayer;

import fr.cpe.dp.projet2.model.music.IMusic;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequencer;

/**
 *
 * @author Benoit
 */
public abstract class AbstractMusicPlayer implements IMusicPlayer {
    private IMusic music;
    private Sequencer sequencer;

    public AbstractMusicPlayer() throws MidiUnavailableException {
        this.sequencer = MidiSystem.getSequencer();
    }
    
    public AbstractMusicPlayer(IMusic music) throws MidiUnavailableException {
        this.music = music;
        this.sequencer = MidiSystem.getSequencer();
    }
    
    @Override
    public void pause() {
        sequencer.stop();
    }

    @Override
    public void play() throws InvalidMidiDataException {
        try {
            if(!sequencer.isOpen()) {
                sequencer.open();
                //sequenceur.setTempoInBPM(120);
                sequencer.setSequence(this.music.getSequence());
            }
            sequencer.start();
        } catch (MidiUnavailableException ex) {
            Logger.getLogger(AbstractMusicPlayer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void stop() {
        sequencer.stop();
        sequencer.close();
    }

    @Override
    public IMusic getMusic() {
        return music;
    }

    @Override
    public void setMusic(IMusic music) {
        this.music = music;
    }
    
    @Override
    public Sequencer getSequencer() {
    	return this.sequencer;
    }
}
